<template>
  <div class="system-integration-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>系统集成管理</h1>
      <p class="subtitle">第三方服务集成、API接口管理、访问控制</p>
    </div>

    <!-- 第三方集成管理 -->
    <AppleCard title="第三方服务集成" class="integration-management">
      <div class="integration-grid">
        <div 
          v-for="(integration, type) in integrationList.integrations" 
          :key="type"
          class="integration-card"
          :class="{ 'integration-enabled': integration.enabled }"
        >
          <div class="integration-header">
            <div class="integration-icon">
              <i :class="getIntegrationIcon(type)"></i>
            </div>
            <div class="integration-info">
              <h3>{{ getIntegrationName(type) }}</h3>
              <span class="integration-status" :class="integration.enabled ? 'enabled' : 'disabled'">
                {{ integration.enabled ? '已启用' : '已禁用' }}
              </span>
            </div>
            <div class="integration-actions">
              <AppleButton
                :type="integration.enabled ? 'warning' : 'primary'"
                size="small"
                @click="toggleIntegration(type, !integration.enabled)"
              >
                {{ integration.enabled ? '禁用' : '启用' }}
              </AppleButton>
              <AppleButton
                type="outline"
                size="small"
                @click="configureIntegration(type)"
              >
                配置
              </AppleButton>
            </div>
          </div>

          <div class="integration-details">
            <div class="detail-item">
              <span class="label">最后测试:</span>
              <span class="value" v-if="integration.last_test">
                <span :class="integration.last_test.success ? 'status-success' : 'status-failed'">
                  {{ integration.last_test.success ? '成功' : '失败' }}
                </span>
                <small>{{ formatDateTime(integration.last_test.test_time) }}</small>
              </span>
              <span class="value" v-else>未测试</span>
            </div>
            <div class="detail-actions">
              <AppleButton
                type="text"
                size="small"
                @click="testConnection(type)"
                :loading="testingConnections[type]"
              >
                测试连接
              </AppleButton>
              <AppleButton
                type="text"
                size="small"
                @click="syncData(type)"
                :loading="syncingData[type]"
                :disabled="!integration.enabled"
              >
                数据同步
              </AppleButton>
            </div>
          </div>
        </div>
      </div>
    </AppleCard>

    <!-- API接口管理 -->
    <AppleCard title="API接口管理" class="api-management">
      <div class="api-overview">
        <div class="overview-stats">
          <div class="stat-card">
            <div class="stat-number">{{ apiStatistics.request_stats?.total_requests || 0 }}</div>
            <div class="stat-label">总请求数</div>
          </div>
          <div class="stat-card">
            <div class="stat-number">{{ apiStatistics.request_stats?.unique_users || 0 }}</div>
            <div class="stat-label">活跃用户</div>
          </div>
          <div class="stat-card">
            <div class="stat-number">{{ apiStatistics.request_stats?.error_rate_percent?.toFixed(1) || 0 }}%</div>
            <div class="stat-label">错误率</div>
          </div>
          <div class="stat-card">
            <div class="stat-number">{{ accessRules.active_count || 0 }}</div>
            <div class="stat-label">访问规则</div>
          </div>
        </div>

        <div class="overview-actions">
          <AppleSelect
            v-model="apiTimeRange"
            :options="timeRangeOptions"
            placeholder="时间范围"
            class="time-range-select"
            @change="loadApiStatistics"
          />
          <AppleButton
            type="outline"
            @click="loadApiStatistics"
            :loading="apiLoading"
          >
            刷新数据
          </AppleButton>
          <AppleButton
            type="primary"
            @click="showApiReportModal = true"
          >
            生成报告
          </AppleButton>
        </div>
      </div>

      <!-- API监控图表 -->
      <div class="api-monitoring-section">
        <h4>API请求趋势</h4>
        <div class="monitoring-controls">
          <AppleSelect
            v-model="monitoringGroupBy"
            :options="groupByOptions"
            placeholder="分组方式"
            class="group-select"
            @change="loadApiMonitoring"
          />
        </div>
        <div class="monitoring-chart">
          <canvas ref="apiChart" width="800" height="300"></canvas>
        </div>
      </div>

      <!-- 热门接口 -->
      <div class="top-endpoints-section">
        <h4>热门接口 Top 10</h4>
        <div class="endpoints-list">
          <div 
            v-for="endpoint in apiMonitoring.top_endpoints?.slice(0, 10)" 
            :key="endpoint.endpoint"
            class="endpoint-item"
          >
            <span class="endpoint-path">{{ endpoint.endpoint }}</span>
            <span class="endpoint-count">{{ endpoint.request_count }}</span>
            <span class="endpoint-percentage">{{ endpoint.percentage }}%</span>
          </div>
        </div>
      </div>
    </AppleCard>

    <!-- 访问控制规则 -->
    <AppleCard title="访问控制规则" class="access-control">
      <div class="access-control-header">
        <div class="rule-stats">
          <span>总规则: {{ accessRules.total_count || 0 }}</span>
          <span>已启用: {{ accessRules.active_count || 0 }}</span>
        </div>
        <AppleButton
          type="primary"
          @click="showCreateRuleModal = true"
        >
          新增规则
        </AppleButton>
      </div>

      <AppleTable
        :columns="ruleColumns"
        :data="accessRules.rules || []"
        :loading="rulesLoading"
        class="rules-table"
      >
        <template #enabled="{ record }">
          <span :class="record.enabled ? 'status-enabled' : 'status-disabled'">
            {{ record.enabled ? '已启用' : '已禁用' }}
          </span>
        </template>
        <template #action="{ record }">
          <span :class="record.action === 'allow' ? 'action-allow' : 'action-deny'">
            {{ record.action === 'allow' ? '允许' : '拒绝' }}
          </span>
        </template>
        <template #actions="{ record }">
          <AppleButton
            type="text"
            size="small"
            @click="editAccessRule(record)"
          >
            编辑
          </AppleButton>
          <AppleButton
            type="text"
            size="small"
            @click="toggleAccessRule(record)"
          >
            {{ record.enabled ? '禁用' : '启用' }}
          </AppleButton>
          <AppleButton
            type="text"
            size="small"
            danger
            @click="deleteAccessRule(record)"
          >
            删除
          </AppleButton>
        </template>
      </AppleTable>
    </AppleCard>

    <!-- 集成配置弹窗 -->
    <AppleModal
      v-model:visible="showConfigModal"
      :title="`配置${getIntegrationName(currentIntegrationType)}`"
      width="600px"
      class="config-modal"
    >
      <div class="config-form">
        <div v-for="(field, key) in getConfigFields(currentIntegrationType)" :key="key" class="form-group">
          <label :for="key">{{ field.label }}:</label>
          <AppleInput
            :id="key"
            v-model="integrationConfig[key]"
            :type="field.type"
            :placeholder="field.placeholder"
            :required="field.required"
          />
        </div>
      </div>
      <template #footer>
        <AppleButton @click="showConfigModal = false">取消</AppleButton>
        <AppleButton
          type="primary"
          :loading="configLoading"
          @click="saveIntegrationConfig"
        >
          保存配置
        </AppleButton>
      </template>
    </AppleModal>

    <!-- 访问规则弹窗 -->
    <AppleModal
      v-model:visible="showCreateRuleModal"
      :title="editingRule ? '编辑访问规则' : '新增访问规则'"
      width="600px"
      class="rule-modal"
    >
      <div class="rule-form">
        <div class="form-group">
          <label>规则名称:</label>
          <AppleInput
            v-model="ruleForm.name"
            placeholder="请输入规则名称"
          />
        </div>
        <div class="form-group">
          <label>规则类型:</label>
          <AppleSelect
            v-model="ruleForm.rule_type"
            :options="ruleTypeOptions"
            placeholder="选择规则类型"
          />
        </div>
        <div class="form-group">
          <label>执行动作:</label>
          <AppleSelect
            v-model="ruleForm.action"
            :options="actionOptions"
            placeholder="选择执行动作"
          />
        </div>
        <div class="form-group">
          <label>条件配置:</label>
          <textarea
            v-model="ruleForm.conditions_json"
            class="conditions-textarea"
            placeholder="请输入JSON格式的条件配置"
            rows="6"
          ></textarea>
        </div>
        <div class="form-group">
          <label>描述:</label>
          <AppleInput
            v-model="ruleForm.description"
            placeholder="请输入规则描述"
          />
        </div>
      </div>
      <template #footer>
        <AppleButton @click="showCreateRuleModal = false">取消</AppleButton>
        <AppleButton
          type="primary"
          :loading="ruleLoading"
          @click="saveAccessRule"
        >
          {{ editingRule ? '更新' : '创建' }}
        </AppleButton>
      </template>
    </AppleModal>

    <!-- API报告弹窗 -->
    <AppleModal
      v-model:visible="showApiReportModal"
      title="生成API报告"
      width="500px"
      class="report-modal"
    >
      <div class="report-form">
        <div class="form-group">
          <label>报告类型:</label>
          <AppleSelect
            v-model="reportConfig.report_type"
            :options="reportTypeOptions"
            placeholder="选择报告类型"
          />
        </div>
        <div class="form-group">
          <label>时间范围:</label>
          <AppleSelect
            v-model="reportConfig.time_range"
            :options="timeRangeOptions"
            placeholder="选择时间范围"
          />
        </div>
      </div>
      <template #footer>
        <AppleButton @click="showApiReportModal = false">取消</AppleButton>
        <AppleButton
          type="primary"
          :loading="reportLoading"
          @click="generateApiReport"
        >
          生成报告
        </AppleButton>
      </template>
    </AppleModal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useMessage } from '@/composables/useMessage'
import { integrationApi } from '@/api/system'
import AppleCard from '@/components/ui/AppleCard.vue'
import AppleButton from '@/components/ui/AppleButton.vue'
import AppleSelect from '@/components/ui/AppleSelect.vue'
import AppleTable from '@/components/ui/AppleTable.vue'
import AppleModal from '@/components/ui/AppleModal.vue'
import AppleInput from '@/components/ui/AppleInput.vue'
import type {
  IntegrationList,
  ApiStatistics,
  ApiMonitoringData,
  AccessRuleList,
  AccessRule,
  ApiReportRequest
} from '@/types/system'

// 响应式数据
const integrationList = reactive<IntegrationList>({
  integrations: {},
  total_count: 0,
  enabled_count: 0
})

const apiStatistics = reactive<ApiStatistics>({
  time_range_hours: 24,
  request_stats: {
    total_requests: 0,
    unique_users: 0,
    unique_ips: 0,
    error_requests: 0,
    error_rate_percent: 0
  },
  distributions: {
    hourly: [],
    status_codes: []
  },
  generated_at: ''
})

const apiMonitoring = reactive<ApiMonitoringData>({
  time_range: {
    start: '',
    end: '',
    hours: 24
  },
  summary: {
    total_requests: 0,
    success_requests: 0,
    error_requests: 0,
    success_rate_percent: 0
  },
  response_time: {
    average_ms: 0,
    median_ms: 0,
    p95_ms: 0,
    p99_ms: 0,
    max_ms: 0
  },
  top_endpoints: [],
  grouped_data: {
    group_by: 'endpoint',
    data: []
  }
})

const accessRules = reactive<AccessRuleList>({
  rules: [],
  total_count: 0,
  active_count: 0
})

// 加载状态
const testingConnections = reactive<Record<string, boolean>>({})
const syncingData = reactive<Record<string, boolean>>({})
const apiLoading = ref(false)
const rulesLoading = ref(false)
const configLoading = ref(false)
const ruleLoading = ref(false)
const reportLoading = ref(false)

// 弹窗状态
const showConfigModal = ref(false)
const showCreateRuleModal = ref(false)
const showApiReportModal = ref(false)

// 表单数据
const currentIntegrationType = ref('')
const integrationConfig = reactive<Record<string, any>>({})
const apiTimeRange = ref(24)
const monitoringGroupBy = ref('endpoint')
const editingRule = ref<AccessRule | null>(null)

const ruleForm = reactive({
  name: '',
  rule_type: '',
  action: 'allow',
  conditions_json: '',
  description: ''
})

const reportConfig = reactive<ApiReportRequest>({
  report_type: 'usage',
  time_range: 24
})

// 配置选项
const timeRangeOptions = [
  { label: '1小时', value: 1 },
  { label: '6小时', value: 6 },
  { label: '12小时', value: 12 },
  { label: '24小时', value: 24 },
  { label: '7天', value: 168 }
]

const groupByOptions = [
  { label: '按接口', value: 'endpoint' },
  { label: '按用户', value: 'user' },
  { label: '按方法', value: 'method' },
  { label: '按状态', value: 'status' }
]

const ruleTypeOptions = [
  { label: 'IP限制', value: 'ip_restriction' },
  { label: '频率限制', value: 'rate_limit' },
  { label: '时间限制', value: 'time_restriction' },
  { label: '用户限制', value: 'user_restriction' }
]

const actionOptions = [
  { label: '允许', value: 'allow' },
  { label: '拒绝', value: 'deny' }
]

const reportTypeOptions = [
  { label: '使用情况', value: 'usage' },
  { label: '安全报告', value: 'security' },
  { label: '性能报告', value: 'performance' },
  { label: '错误报告', value: 'error' }
]

// 表格列配置
const ruleColumns = [
  { title: '规则名称', dataIndex: 'name', key: 'name' },
  { title: '类型', dataIndex: 'rule_type', key: 'rule_type' },
  { title: '动作', dataIndex: 'action', key: 'action', slot: 'action' },
  { title: '状态', dataIndex: 'enabled', key: 'enabled', slot: 'enabled' },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at' },
  { title: '操作', key: 'actions', slot: 'actions', width: '150px' }
]

const apiChart = ref<HTMLCanvasElement>()

const { showMessage } = useMessage()

// 方法
const loadIntegrationList = async () => {
  try {
    const response = await integrationApi.getIntegrationList()
    if (response.success) {
      Object.assign(integrationList, response.data)
    }
  } catch (error) {
    console.error('加载集成列表失败:', error)
  }
}

const loadApiStatistics = async () => {
  apiLoading.value = true
  try {
    const response = await integrationApi.getApiStatistics(apiTimeRange.value)
    if (response.success) {
      Object.assign(apiStatistics, response.data)
    }
  } catch (error) {
    console.error('加载API统计失败:', error)
  } finally {
    apiLoading.value = false
  }
}

const loadApiMonitoring = async () => {
  try {
    const response = await integrationApi.getApiMonitoring({
      time_range: apiTimeRange.value,
      group_by: monitoringGroupBy.value
    })
    if (response.success) {
      Object.assign(apiMonitoring, response.data)
      drawApiChart()
    }
  } catch (error) {
    console.error('加载API监控失败:', error)
  }
}

const loadAccessRules = async () => {
  rulesLoading.value = true
  try {
    const response = await integrationApi.getAccessRules()
    if (response.success) {
      Object.assign(accessRules, response.data)
    }
  } catch (error) {
    console.error('加载访问规则失败:', error)
  } finally {
    rulesLoading.value = false
  }
}

const toggleIntegration = async (type: string, enabled: boolean) => {
  try {
    const response = await integrationApi.manageIntegration({
      action: enabled ? 'enable' : 'disable',
      integration_type: type
    })
    
    if (response.success) {
      showMessage.success(`${getIntegrationName(type)}${enabled ? '启用' : '禁用'}成功`)
      await loadIntegrationList()
    }
  } catch (error) {
    showMessage.error(`${getIntegrationName(type)}${enabled ? '启用' : '禁用'}失败`)
    console.error('切换集成状态失败:', error)
  }
}

const configureIntegration = (type: string) => {
  currentIntegrationType.value = type
  
  // 加载当前配置
  const integration = integrationList.integrations[type]
  if (integration?.config) {
    Object.assign(integrationConfig, integration.config)
  } else {
    // 清空配置
    Object.keys(integrationConfig).forEach(key => {
      delete integrationConfig[key]
    })
  }
  
  showConfigModal.value = true
}

const testConnection = async (type: string) => {
  testingConnections[type] = true
  try {
    const response = await integrationApi.testConnection({
      integration_type: type
    })
    
    if (response.success && response.data.success) {
      showMessage.success(`${getIntegrationName(type)}连接测试成功`)
    } else {
      showMessage.error(`${getIntegrationName(type)}连接测试失败`)
    }
    
    await loadIntegrationList()
  } catch (error) {
    showMessage.error(`${getIntegrationName(type)}连接测试失败`)
    console.error('连接测试失败:', error)
  } finally {
    testingConnections[type] = false
  }
}

const syncData = async (type: string) => {
  syncingData[type] = true
  try {
    const response = await integrationApi.syncData({
      integration_type: type,
      sync_type: 'incremental'
    })
    
    if (response.success) {
      showMessage.success(`${getIntegrationName(type)}数据同步启动成功`)
    }
  } catch (error) {
    showMessage.error(`${getIntegrationName(type)}数据同步失败`)
    console.error('数据同步失败:', error)
  } finally {
    syncingData[type] = false
  }
}

const saveIntegrationConfig = async () => {
  configLoading.value = true
  try {
    const response = await integrationApi.manageIntegration({
      action: 'update',
      integration_type: currentIntegrationType.value,
      config_data: integrationConfig
    })
    
    if (response.success) {
      showMessage.success('集成配置保存成功')
      showConfigModal.value = false
      await loadIntegrationList()
    }
  } catch (error) {
    showMessage.error('集成配置保存失败')
    console.error('保存配置失败:', error)
  } finally {
    configLoading.value = false
  }
}

const editAccessRule = (rule: AccessRule) => {
  editingRule.value = rule
  ruleForm.name = rule.name
  ruleForm.rule_type = rule.rule_type
  ruleForm.action = rule.action
  ruleForm.conditions_json = JSON.stringify(rule.conditions, null, 2)
  ruleForm.description = rule.description || ''
  showCreateRuleModal.value = true
}

const saveAccessRule = async () => {
  ruleLoading.value = true
  try {
    const conditions = JSON.parse(ruleForm.conditions_json)
    
    const response = await integrationApi.manageAccessRules({
      action: editingRule.value ? 'update' : 'create',
      access_config: {
        rule_id: editingRule.value?.rule_id,
        name: ruleForm.name,
        rule_type: ruleForm.rule_type,
        action: ruleForm.action,
        conditions,
        description: ruleForm.description
      }
    })
    
    if (response.success) {
      showMessage.success(`访问规则${editingRule.value ? '更新' : '创建'}成功`)
      showCreateRuleModal.value = false
      resetRuleForm()
      await loadAccessRules()
    }
  } catch (error) {
    showMessage.error(`访问规则${editingRule.value ? '更新' : '创建'}失败`)
    console.error('保存访问规则失败:', error)
  } finally {
    ruleLoading.value = false
  }
}

const toggleAccessRule = async (rule: AccessRule) => {
  try {
    const response = await integrationApi.manageAccessRules({
      action: rule.enabled ? 'disable' : 'enable',
      access_config: {
        rule_id: rule.rule_id
      }
    })
    
    if (response.success) {
      showMessage.success(`访问规则${rule.enabled ? '禁用' : '启用'}成功`)
      await loadAccessRules()
    }
  } catch (error) {
    showMessage.error(`访问规则${rule.enabled ? '禁用' : '启用'}失败`)
    console.error('切换访问规则失败:', error)
  }
}

const deleteAccessRule = async (rule: AccessRule) => {
  try {
    const response = await integrationApi.manageAccessRules({
      action: 'delete',
      access_config: {
        rule_id: rule.rule_id
      }
    })
    
    if (response.success) {
      showMessage.success('访问规则删除成功')
      await loadAccessRules()
    }
  } catch (error) {
    showMessage.error('访问规则删除失败')
    console.error('删除访问规则失败:', error)
  }
}

const generateApiReport = async () => {
  reportLoading.value = true
  try {
    const response = await integrationApi.generateReport(reportConfig)
    
    if (response.success) {
      showMessage.success('API报告生成成功')
      showApiReportModal.value = false
      // 这里可以下载报告或显示报告内容
    }
  } catch (error) {
    showMessage.error('API报告生成失败')
    console.error('生成报告失败:', error)
  } finally {
    reportLoading.value = false
  }
}

const resetRuleForm = () => {
  editingRule.value = null
  ruleForm.name = ''
  ruleForm.rule_type = ''
  ruleForm.action = 'allow'
  ruleForm.conditions_json = ''
  ruleForm.description = ''
}

// 工具方法
const getIntegrationName = (type: string): string => {
  const names: Record<string, string> = {
    email: '邮件服务',
    sms: '短信服务',
    payment: '支付服务',
    storage: '存储服务'
  }
  return names[type] || type
}

const getIntegrationIcon = (type: string): string => {
  const icons: Record<string, string> = {
    email: 'icon-email',
    sms: 'icon-message',
    payment: 'icon-payment',
    storage: 'icon-storage'
  }
  return icons[type] || 'icon-default'
}

const getConfigFields = (type: string) => {
  const fields: Record<string, Record<string, any>> = {
    email: {
      smtp_server: { label: 'SMTP服务器', type: 'text', placeholder: '如: smtp.gmail.com', required: true },
      smtp_port: { label: 'SMTP端口', type: 'number', placeholder: '587', required: true },
      username: { label: '用户名', type: 'email', placeholder: '邮箱地址', required: true },
      password: { label: '密码', type: 'password', placeholder: '应用密码', required: true }
    },
    sms: {
      provider: { label: '服务商', type: 'text', placeholder: '如: aliyun', required: true },
      api_endpoint: { label: 'API地址', type: 'url', placeholder: 'API接口地址', required: true },
      api_key: { label: 'API Key', type: 'text', placeholder: 'API密钥', required: true },
      secret: { label: 'Secret', type: 'password', placeholder: '密钥', required: true }
    },
    payment: {
      provider: { label: '支付商', type: 'text', placeholder: '如: alipay', required: true },
      app_id: { label: 'App ID', type: 'text', placeholder: '应用ID', required: true },
      secret_key: { label: '密钥', type: 'password', placeholder: '私钥', required: true },
      sandbox_mode: { label: '沙箱模式', type: 'text', placeholder: 'true/false', required: false }
    },
    storage: {
      provider: { label: '存储商', type: 'text', placeholder: '如: aliyun', required: true },
      access_key: { label: 'Access Key', type: 'text', placeholder: '访问密钥', required: true },
      secret_key: { label: 'Secret Key', type: 'password', placeholder: '密钥', required: true },
      bucket: { label: 'Bucket', type: 'text', placeholder: '存储桶名称', required: true },
      region: { label: '区域', type: 'text', placeholder: '存储区域', required: true }
    }
  }
  return fields[type] || {}
}

const formatDateTime = (dateStr: string): string => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const drawApiChart = () => {
  if (!apiChart.value) return
  
  const ctx = apiChart.value.getContext('2d')
  if (!ctx) return
  
  ctx.clearRect(0, 0, apiChart.value.width, apiChart.value.height)
  ctx.fillStyle = '#007AFF'
  ctx.fillText(`API请求趋势图 (${apiMonitoring.grouped_data.data.length} 个数据点)`, 10, 20)
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadIntegrationList(),
    loadApiStatistics(),
    loadApiMonitoring(),
    loadAccessRules()
  ])
})
</script>

<style scoped lang="scss">
.system-integration-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 24px;
    
    h1 {
      margin: 0 0 8px 0;
      font-size: 28px;
      font-weight: 600;
      color: #1d1d1f;
    }
    
    .subtitle {
      margin: 0;
      color: #6e6e73;
      font-size: 16px;
    }
  }
  
  // 第三方集成样式
  .integration-management {
    margin-bottom: 24px;
    
    .integration-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
      gap: 20px;
      
      .integration-card {
        padding: 20px;
        border: 2px solid #f2f2f7;
        border-radius: 12px;
        transition: all 0.3s ease;
        
        &.integration-enabled {
          border-color: #30d158;
          background: #f5fff8;
        }
        
        &:hover {
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
        }
        
        .integration-header {
          display: flex;
          align-items: center;
          margin-bottom: 16px;
          
          .integration-icon {
            width: 48px;
            height: 48px;
            background: #f2f2f7;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 16px;
            
            i {
              font-size: 24px;
              color: #007aff;
            }
          }
          
          .integration-info {
            flex: 1;
            
            h3 {
              margin: 0 0 4px 0;
              font-size: 16px;
              font-weight: 600;
              color: #1d1d1f;
            }
            
            .integration-status {
              font-size: 12px;
              padding: 2px 8px;
              border-radius: 6px;
              
              &.enabled {
                background: #d1f2eb;
                color: #00875a;
              }
              
              &.disabled {
                background: #ffecee;
                color: #de350b;
              }
            }
          }
          
          .integration-actions {
            display: flex;
            gap: 8px;
          }
        }
        
        .integration-details {
          .detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            
            .label {
              color: #6e6e73;
              font-size: 14px;
            }
            
            .value {
              font-size: 14px;
              
              .status-success { color: #30d158; }
              .status-failed { color: #ff3b30; }
              
              small {
                display: block;
                color: #8e8e93;
                font-size: 12px;
              }
            }
          }
          
          .detail-actions {
            display: flex;
            gap: 12px;
            margin-top: 16px;
          }
        }
      }
    }
  }
  
  // API管理样式
  .api-management {
    margin-bottom: 24px;
    
    .api-overview {
      margin-bottom: 24px;
      
      .overview-stats {
        display: flex;
        gap: 16px;
        margin-bottom: 16px;
        flex-wrap: wrap;
        
        .stat-card {
          flex: 1;
          min-width: 120px;
          text-align: center;
          padding: 16px;
          background: #f2f2f7;
          border-radius: 12px;
          
          .stat-number {
            font-size: 24px;
            font-weight: 600;
            color: #007aff;
            margin-bottom: 4px;
          }
          
          .stat-label {
            font-size: 12px;
            color: #6e6e73;
          }
        }
      }
      
      .overview-actions {
        display: flex;
        gap: 12px;
        align-items: center;
        
        .time-range-select {
          width: 150px;
        }
      }
    }
    
    .api-monitoring-section {
      margin-bottom: 24px;
      
      h4 {
        margin: 0 0 16px 0;
        font-size: 16px;
        font-weight: 600;
        color: #1d1d1f;
      }
      
      .monitoring-controls {
        display: flex;
        gap: 12px;
        margin-bottom: 16px;
        
        .group-select {
          width: 150px;
        }
      }
      
      .monitoring-chart {
        background: #f9f9f9;
        border-radius: 12px;
        padding: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 300px;
        
        canvas {
          max-width: 100%;
          height: auto;
        }
      }
    }
    
    .top-endpoints-section {
      h4 {
        margin: 0 0 16px 0;
        font-size: 16px;
        font-weight: 600;
        color: #1d1d1f;
      }
      
      .endpoints-list {
        .endpoint-item {
          display: flex;
          align-items: center;
          padding: 12px 16px;
          background: #f9f9f9;
          border-radius: 8px;
          margin-bottom: 8px;
          
          .endpoint-path {
            flex: 1;
            font-family: monospace;
            font-size: 14px;
            color: #1d1d1f;
          }
          
          .endpoint-count {
            margin-right: 16px;
            font-weight: 600;
            color: #007aff;
          }
          
          .endpoint-percentage {
            min-width: 60px;
            text-align: right;
            color: #6e6e73;
            font-size: 14px;
          }
        }
      }
    }
  }
  
  // 访问控制样式
  .access-control {
    .access-control-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .rule-stats {
        display: flex;
        gap: 16px;
        font-size: 14px;
        color: #6e6e73;
      }
    }
    
    .rules-table {
      .status-enabled { color: #30d158; }
      .status-disabled { color: #8e8e93; }
      .action-allow { color: #30d158; }
      .action-deny { color: #ff3b30; }
    }
  }
  
  // 弹窗样式
  .config-form, .rule-form, .report-form {
    .form-group {
      margin-bottom: 16px;
      
      label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        color: #1d1d1f;
      }
      
      .conditions-textarea {
        width: 100%;
        padding: 12px;
        border: 1px solid #d1d1d6;
        border-radius: 8px;
        font-family: monospace;
        font-size: 14px;
        resize: vertical;
        
        &:focus {
          outline: none;
          border-color: #007aff;
          box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .system-integration-container {
    padding: 16px;
    
    .integration-grid {
      grid-template-columns: 1fr;
    }
    
    .overview-stats {
      flex-direction: column;
    }
    
    .overview-actions {
      flex-direction: column;
      align-items: stretch;
      
      .time-range-select {
        width: 100%;
      }
    }
    
    .access-control-header {
      flex-direction: column;
      align-items: stretch;
      gap: 12px;
    }
  }
}
</style>